package com.spring.sso.config.security.authentication;

import com.alibaba.fastjson.JSON;
import com.beust.jcommander.internal.Lists;
import com.google.common.collect.Maps;
import com.spring.sso.common.CommonResult;
import com.spring.sso.common.Constant;
import com.spring.sso.common.DefaultUserDetails;
import com.spring.sso.config.security.cookie.CookieService;
import com.spring.sso.config.util.ApplicationContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author : pangfuzhong
 * @description
 * @date : 2021/9/22 09:07
 */
@Slf4j
public class RemoteAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public void setUsernameParameter(String parameter) {
        super.setUsernameParameter(parameter);
    }

    @Override
    public void setPasswordParameter(String parameter) {
        super.setPasswordParameter(parameter);
    }

    /*@Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        } else {
            String username = this.obtainUsername(request);
            username = username != null ? username : "";
            username = username.trim();
            String password = this.obtainPassword(request);
            password = password != null ? password : "";
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
            this.setDetails(request, authRequest);
            authRequest.setDetails(request.getRequestURL().toString());
            return this.getAuthenticationManager().authenticate(authRequest);
        }
    }*/

    @Override
    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        super.setAuthenticationManager(authenticationManager);
    }

    @Override
    public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler authenticationSuccessHandler) {
        if(!Objects.isNull(authenticationSuccessHandler)) {
            super.setAuthenticationSuccessHandler(authenticationSuccessHandler);
            return;
        }
        super.setAuthenticationSuccessHandler(new AuthenticationSuccessHandler() {
            @Override
            public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                // 认证成功
                DefaultUserDetails defaultUserDetails = (DefaultUserDetails) authentication.getDetails();
                defaultUserDetails.setPassword("");

                // 设置cookie
                //CookieService cookieService = (CookieService) ApplicationContextUtil.getBeanByType(CookieService.class);
                //cookieService.setCookie(request, response, "TOKEN", userDetails.getAccessToke(), userDetails.getExpireTime(), Boolean.FALSE);

                // 返回
                response.setContentType("application/json; chartset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                try {
                    response.getWriter().write(JSON.toJSONString(defaultUserDetails));
                    response.getWriter().flush();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    SecurityContextHolder.clearContext();
                }
            }
        });
    }

    @Override
    public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
        if(!Objects.isNull(authenticationFailureHandler)) {
            super.setAuthenticationFailureHandler(authenticationFailureHandler);
            return;
        }
        super.setAuthenticationFailureHandler(new AuthenticationFailureHandler() {
            @Override
            public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
                // 认证失败
            }
        });
    }
}
